%%% @doc
%%% обновление окна по таймеру. Работает на главной ноде
%%% @end
-module(info_updater).
-export([init/2, stop/0, start/1, update/0]).

start(Node) ->
  application:load(ssu2015DeviceTest),
  case whereis(info_updater) of
    undefined ->
      WindowPid = self(),
      spawn(Node, info_updater, init, [node(), WindowPid]),
      receive
        updater_started ->
          ok
      end;
    Pid ->
      error(Pid)
  end.

init(Node, WindowPid) when is_pid(WindowPid) ->
  register(info_updater, self()),
  pong = net_adm:ping(Node),
  Node, WindowPid ! updater_started,
  event_loop(Node, WindowPid).

-spec event_loop/2 :: (node(), pid()) -> ok.
event_loop(Node, WindowPid) ->
  case application:get_env(default_timespan) of
    undefined ->
      try
        io:format("default_timespan undefined~n"),
        ok
      of
        ok -> ok
      catch _:_ -> ok
      end;
    {ok, DefaultTimespan} ->
      receive
        update ->
          update(Node, WindowPid),
          event_loop(Node, WindowPid);

        {info_stop, From} when is_pid(From) ->
          From ! {info, stopped},
          ok

      after DefaultTimespan
        ->
        self() ! update,
        event_loop(Node, WindowPid)
      end
  end.

-spec update/2 :: (node(), pid()) -> ok.
update(Node, WindowPid) ->
  Result = storage_supervisor:get_current_states(),
  Node, WindowPid ! {updateGrid, Result, node(), self()},
  receive
    updated_grid ->
      ok
  end.

-spec update/0 :: () -> update.
update() ->
  info_updater ! update.

-spec stop/0 :: () -> ok.
stop() ->
  try
    info_updater ! {info_stop, self()},
    receive
      {info, stopped} ->
        io:format("info updater finished correctly~n"),
        ok
    end

  of
    ok -> ok
  catch error:badarg -> ok
  end.